<template>
  <div>
    <div class="uploadImage">
      <froala
        id="edit"
        ref="editS"
        v-model="model"
        :tag="'textarea'"
        :config="config"
      />
      <el-upload
        class="uploadimage"
        :on-error="handleAvatarError"
        :on-success="handleAvatarSuccessImg"
        :before-upload="beforeUpload"
        name="multipartFile"
        :action="action"
        :show-file-list="false"
      >
        <i ref="uploadBtn" class="el-icon-picture" />
      </el-upload>
    </div>
  </div>
</template>

<script>
import { HTTP_URI } from '@/api/baseUrl'
export default {
  components: {},
  props: {
    content: {}
  },

  data() {
    var _this = this
    return {
      action: HTTP_URI.UPLOADIMG,
      config: {
        editor: null,
        lastEditRange: null,
        body: null,
        language: 'zh_cn',
        height: 325,
        quickInsertEnabled: false,
        charCounterCount: false,

        toolbarButtons: [
          'fullscreen',
          'bold',
          'italic',
          'underline',
          // 'strikeThrough',
          // 'subscript',
          // 'superscript',
          // '|',
          'fontFamily',
          'fontSize',
          'color',
          'textColor',
          // 'inlineClass',
          // 'inlineStyle',
          'paragraphStyle',
          'lineHeight',
          // '|',
          'paragraphFormat',
          'align',
          'formatOL',
          'formatUL',
          'outdent',
          'indent',
          // 'quote',
          // 'insertLink',
          // 'insertImage',
          //   "insertVideo",
          //   "embedly",
          //   "insertFile",
          // 'insertTable',
          // '|',
          // 'emoticons',
          // 'fontAwesome',
          // 'specialCharacters',
          // 'insertHR',
          // 'selectAll',
          'clearFormatting',
          // '|',
          // "print",
          // "getPDF",
          // 'spellChecker',
          // 'help',
          // 'html',
          // '|',
          'undo',
          'redo'
        ],
        colorsBackground: [
          '#15E67F',
          '#E3DE8C',
          '#D8A076',
          '#D83762',
          '#76B6D8',
          'REMOVE',
          '#1C7A90',
          '#249CB8',
          '#4ABED9',
          '#FBD75B',
          '#FBE571',
          '#FFFFFF'
        ],
        colorsStep: 12,
        colorsText: [
          '#333333',
          '#15E67F',
          '#E3DE8C',
          '#D8A076',
          '#D83762',
          '#76B6D8',
          'REMOVE',
          '#1C7A90',
          '#249CB8',
          '#4ABED9',
          '#FBD75B',
          '#FBE571',
          '#FFFFFF'
        ],
        imageEditButtons: [
          'imageReplace',
          'imageAlign',
          'imageCaption',
          'imageRemove'
        ],

        imageUploadMethod: 'POST',
        // Allow to upload PNG and JPG.
        imageAllowedTypes: ['jpeg', 'jpg', 'png'],
        placeholderText: '请输入内容',
        // Set max file size to 20MB.
        fileMaxSize: 20 * 1024 * 1024,
        toolbarSticky: false,
        // Allow to upload any file.
        fileAllowedTypes: ['*'],
        events: {
          initialized: (e, editor) => {
            this.editor = this.$refs.editS.getEditor()
          },
          // 添加事件，在每次按键按下时，都记录一下最后停留位置
          keyup: (e, editor) => {
            const sel = window.getSelection && window.getSelection()
            if (sel && sel.rangeCount > 0) {
              _this.lastEditRange = sel.getRangeAt(0)
            }
          },
          blur: (e) => {
            this.$emit('change', e.currentTarget.innerHTML)
          }

        }
      }
    }
  },

  computed: {
    model: {
      get() {
        return this.content
      },
      set(val) {
        // 触发更新文本数据
        this.$emit('update:content', val)
      }
    }
  },

  watch: {},

  created() {},

  mounted() {
  },

  methods: {
    handleAvatarError() {
      this.$message.warning('网络繁忙，请稍后上传')
    },
    beforeUpload(file) {
      if (file.type == 'image/jpeg' || file.type == 'image/png') {
        const isLt10M = file.size / 1024 / 1024 < 10
        if (!isLt10M) this.$message.error('图片大小不能超过10M')
        return isLt10M
      } else {
        this.$message.error('图片格式错误')
        return false
      }
    },
    handleAvatarSuccessImg(res, file) {
      if (file.status == 'success') {
        this.insertHtml('<img src=' + res.data.previewUrl + '/' + res.data.fileName + ' />')
      }
    },
    insertHtml(content) {
      // 设置编辑器获取焦点
      this.editor.events.focus()
      // 获取选定对象
      const selection = getSelection()
      // 判断是否有最后光标对象存在
      if (this.lastEditRange) {
        // 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
        selection.removeAllRanges()
        selection.addRange(this.lastEditRange)
      }
      // 插入内容
      this.editor.html.insert(content)
      // 记录最后光标停留位置
      this.lastEditRange = selection.getRangeAt(0)
      console.log(this.lastEditRange)
    }
  }
}
</script>
<style scoped lang="scss">
.fr-uploading {
  display: none;
}
.uploadImage {
  position: relative;
  .el-icon-picture {
    font-size: 18px;
    position: absolute;
    top: 15px;
    right: 20px;
    cursor: pointer;
  }
  .el-icon-picture:before {
    color: black;
  }
}
</style>

<style>
 .fr-wrapper > div {
   margin-top: -20px;
}
 .fr-wrapper > div > a{
   opacity: 0;
 }
/*.fr-element.fr-view {
   position: absolute;
   top: 0;
} */
.fr-placeholder {
   margin-top: 0 !important;
}
p{
  margin: 0;
  padding: 0;
}
.fr-second-toolbar #fr-logo{
  display: none!important;
}
</style>
